package org.szgb.console.ht.electricity.web;

import cn.hutool.http.HttpStatus;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.xssf.usermodel.DefaultIndexedColorMap;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.szgb.console.ht.electricity.entity.*;
import org.szgb.console.ht.electricity.service.HtElectricityPriceService;
import org.szgb.console.ht.electricity.service.HtElectricitySettlementBillItemService;
import org.szgb.console.ht.electricity.service.HtElectricitySettlementBillService;
import org.szgb.console.ht.electricity.service.HtElectricityUsageService;
import org.szgb.console.ht.meter.entity.HtMeterReadingDaily;
import org.szgb.console.ht.meter.service.HtMeterReadingDailyService;
import org.szgb.console.sys.user.entity.SysUser;
import org.szgb.console.utils.PageView;
import org.szgb.console.utils.TokenUtil;
import org.szgb.console.utils.excel.ExportExcel;
import org.szgb.core.base.entity.GetIdDto;
import org.szgb.core.utils.AjaxJson;

import java.awt.*;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;

@Slf4j
@RestController
@RequestMapping(value = "/ht/electricity/settlement/bill")
@Tag(name = "电量结算单管理", description = "电量结算单管理模块")
public class HtElectricitySettlementBillController {
    private final HtElectricitySettlementBillService htElectricitySettlementBillService;
    private final HtElectricitySettlementBillItemService htElectricitySettlementBillItemService;
    private final HtElectricityPriceService htElectricityPriceService;
    private final HtElectricityUsageService htElectricityUsageService;
    private final HtMeterReadingDailyService htMeterReadingDailyService;

    @Autowired
    public HtElectricitySettlementBillController(HtElectricitySettlementBillService htElectricitySettlementBillService, HtElectricityPriceService htElectricityPriceService, HtElectricityUsageService htElectricityUsageService, HtMeterReadingDailyService htMeterReadingDailyService, HtElectricitySettlementBillItemService htElectricitySettlementBillItemService) {
        this.htElectricitySettlementBillService = htElectricitySettlementBillService;
        this.htElectricitySettlementBillItemService = htElectricitySettlementBillItemService;
        this.htElectricityPriceService = htElectricityPriceService;
        this.htElectricityUsageService = htElectricityUsageService;
        this.htMeterReadingDailyService = htMeterReadingDailyService;
    }


    @Operation(summary = "获取电量结算单信息", description = "根据查询参数获取电量结算单信息，支持分页查询。使用id获取更详细的信息。")
    @PostMapping("/get")
    public AjaxJson get(@RequestBody(required = false) HtElectricitySettlementBill.HtElectricitySettlementBillFindDto htElectricitySettlementBillFindDto, HttpServletRequest request, HttpServletResponse response) {
        if (htElectricitySettlementBillFindDto == null) {
            htElectricitySettlementBillFindDto = new HtElectricitySettlementBill.HtElectricitySettlementBillFindDto();
        }
        // 创建一个PageView对象，用于分页显示
        PageView<HtElectricitySettlementBill.HtElectricitySettlementBillView> pageView = new PageView<>();
        HtElectricitySettlementBill htElectricitySettlementBill = htElectricitySettlementBillFindDto.toHtElectricitySettlementBill();
        // 如果实体对象的ID不为空，则直接调用get方法获取单个实体对象
        if (htElectricitySettlementBill != null && htElectricitySettlementBill.getId() != null && !htElectricitySettlementBill.getId().isEmpty()) {
            HtElectricitySettlementBill electricitySettlementBill = htElectricitySettlementBillService.get(htElectricitySettlementBill.getId());
            // 如果实体对象为空，则返回错误响应
            if (electricitySettlementBill == null) {
                return AjaxJson.error("数据不存在", HttpStatus.HTTP_NOT_FOUND, request, response);
            }
            // 返回成功的响应，并将实体对象放入响应中
            return AjaxJson.success(request, response).put("htElectricitySettlementBill", electricitySettlementBill.toHtElectricitySettlementBillView());
        } else {
            // 设置Page对象的列表属性，包含根据实体对象查询到的数据
            pageView.setList(HtElectricitySettlementBill.HtElectricitySettlementBillView.getViewListFromList(htElectricitySettlementBillService.findList(htElectricitySettlementBill)));
            // 设置Page对象的总记录数属性，用于分页显示
            pageView.setCount(htElectricitySettlementBillService.getCount(htElectricitySettlementBill));
            // 创建一个成功的AjaxJson对象，并放入Page对象，以便于前端展示
            return AjaxJson.success(request, response).put("page", pageView);
        }
    }

    @Operation(summary = "获取电量结算单展示信息", description = "根据查询参数获取电量结算单展示信息。")
    @PostMapping("/show")
    public AjaxJson show(@RequestBody GetIdDto idDto, HttpServletRequest request, HttpServletResponse response) {
        HtElectricitySettlementBill htElectricitySettlementBill = htElectricitySettlementBillService.get(idDto.getId());
        if (htElectricitySettlementBill == null) {
            return AjaxJson.error("数据不存在", HttpStatus.HTTP_NOT_FOUND, request, response);
        }
        HtElectricitySettlementBillItem htElectricitySettlementBillItem = new HtElectricitySettlementBillItem();
        htElectricitySettlementBillItem.setHtElectricitySettlementBill(htElectricitySettlementBill);
        List<HtElectricitySettlementBillItem> list = htElectricitySettlementBillItemService.findList(htElectricitySettlementBillItem);
        List<HtElectricitySettlementBillItem.HtElectricitySettlementBillItemView> list1 = HtElectricitySettlementBillItem.HtElectricitySettlementBillItemView.getViewListFromList(list);
        // 返回成功的响应，并将实体对象放入响应中
        return AjaxJson.success(request, response).put("htElectricitySettlementBillShowView", htElectricitySettlementBill.toHtElectricitySettlementBillShowView(list1));

    }


    @PostMapping("/save")
    @Operation(summary = "保存电量结算单", description = "新增或更改电量结算单信息。")
    public AjaxJson save(@RequestBody HtElectricitySettlementBill.HtElectricitySettlementBillSaveDto htElectricitySettlementBillSaveDto, HttpServletRequest request, HttpServletResponse response) {
        if (htElectricitySettlementBillSaveDto == null) {
            return AjaxJson.error("参数错误", HttpStatus.HTTP_BAD_REQUEST, request, response);
        }
        HtElectricitySettlementBill htElectricitySettlementBill = htElectricitySettlementBillSaveDto.toHtElectricitySettlementBill();
        // 设置实体对象的更新者为当前用户
        htElectricitySettlementBill.setUpdatedBy(new SysUser(TokenUtil.getUid(request)));
        // 调用服务层的save方法，尝试保存或更新实体对象，返回保存结果的Map
        htElectricitySettlementBillService.save(htElectricitySettlementBill);
        // 根据保存结果返回相应的AjaxJson对象
        return AjaxJson.success("保存成功", request, response).put("htElectricitySettlementBill", htElectricitySettlementBill.toHtElectricitySettlementBillView());
    }

    @PostMapping("/create")
    @Operation(summary = "生成电量结算单", description = "生成电量结算单信息。")
    public AjaxJson create(@RequestBody HtElectricitySettlementBill.HtElectricitySettlementBillCreateDto htElectricitySettlementBillCreateDto, HttpServletRequest request, HttpServletResponse response) {
        if (htElectricitySettlementBillCreateDto == null) {
            return AjaxJson.error("参数错误", HttpStatus.HTTP_BAD_REQUEST, request, response);
        }
        HtElectricitySettlementBill htElectricitySettlementBill = htElectricitySettlementBillCreateDto.toHtElectricitySettlementBill();
        htElectricitySettlementBill.setUpdatedBy(new SysUser(TokenUtil.getUid(request)));
        // 判断是否已创建
        List<HtElectricitySettlementBill> list = htElectricitySettlementBillService.findList(htElectricitySettlementBill);
        if (!list.isEmpty()) {
            return AjaxJson.error("数据已存在，请先删除", 413, request, response);
        }
        // 查询电价是否录入
        HtElectricityPrice htElectricityPrice = new HtElectricityPrice();
        htElectricityPrice.setMonth(htElectricitySettlementBill.getMonth());
        List<HtElectricityPrice> list1 = htElectricityPriceService.findList(htElectricityPrice);
        if (list1.isEmpty()) {
            return AjaxJson.error("缺少电价", 410, request, response);
        }
        htElectricityPrice = list1.getFirst();
        htElectricitySettlementBill.setHtElectricityPrice(htElectricityPrice);
        // 计算结算单
        String htElectricitySettlementBillId = htElectricitySettlementBill.getHtElectricitySettlementBillModel().getId();
        // 4号线供电合同
        if (Objects.equals(htElectricitySettlementBillId, "68ef3a0a-6c45-4d0d-a7ab-ffe6b525d8dd")) {
            // 查询结算电量是否录入
            HtElectricityUsage usage = new HtElectricityUsage();
            usage.setMonth(htElectricitySettlementBill.getMonth());
            List<HtElectricityUsage> usageList = htElectricityUsageService.findList(usage);
            HtElectricityUsage usage1 = null;
            HtElectricityUsage usage2 = null;
            for (HtElectricityUsage item : usageList) {
                switch (item.getAmmeter().getId()) {
                    case "45f9db2f-f2a5-4d4d-8ed9-afd7e4023a23":
                        usage1 = item;
                        break;
                    case "9c56e558-db7f-445f-89e7-a2e9def93273":
                        usage2 = item;
                        break;
                }
            }
            if (usage1 == null || usage2 == null) {
                return AjaxJson.error("缺少结算电量", 411, request, response);
            }
            // 查询抄表数据是否完整
            // 获取当前月份的最后一天
            LocalDate lastDayOfMonth = htElectricitySettlementBillCreateDto.getMonth().atEndOfMonth();
            // 获取上个月的最后一天
            LocalDate lastDayOfPreviousMonth = htElectricitySettlementBillCreateDto.getMonth().minusMonths(1).atEndOfMonth();

            HtMeterReadingDaily daily301 = null;
            HtMeterReadingDaily daily302 = null;
            HtMeterReadingDaily daily303 = null;
            HtMeterReadingDaily daily304 = null;
            HtMeterReadingDaily dailyPrevious301 = null;
            HtMeterReadingDaily dailyPrevious302 = null;
            HtMeterReadingDaily dailyPrevious303 = null;
            HtMeterReadingDaily dailyPrevious304 = null;
            HtMeterReadingDaily daily = new HtMeterReadingDaily();
            daily.setDate(lastDayOfMonth);
            List<HtMeterReadingDaily> dailyList = htMeterReadingDailyService.findList(daily).stream().filter(daily1 -> daily1.getIsApproval() == true).toList();
            for (HtMeterReadingDaily item : dailyList) {
                switch (item.getTask().getId()) {
                    case "bbf5374b-300c-43af-b0fd-bd1bef8269bd":
                        daily301 = item;
                        break;
                    case "9dcdd4e1-93f4-424d-83ae-8dda3899e9dc":
                        daily302 = item;
                        break;
                    case "348322dc-fa2a-470f-b8ec-7331a028e350":
                        daily303 = item;
                        break;
                    case "5f6e8445-b491-43e6-bc50-9064aea82361":
                        daily304 = item;
                        break;
                }
            }
            HtMeterReadingDaily dailyPrevious = new HtMeterReadingDaily();
            dailyPrevious.setDate(lastDayOfPreviousMonth);
            List<HtMeterReadingDaily> dailyPreviousList = htMeterReadingDailyService.findList(dailyPrevious).stream().filter(item -> item.getIsApproval() == true).toList();
            for (HtMeterReadingDaily item : dailyPreviousList) {
                switch (item.getTask().getId()) {
                    case "bbf5374b-300c-43af-b0fd-bd1bef8269bd":
                        dailyPrevious301 = item;
                        break;
                    case "9dcdd4e1-93f4-424d-83ae-8dda3899e9dc":
                        dailyPrevious302 = item;
                        break;
                    case "348322dc-fa2a-470f-b8ec-7331a028e350":
                        dailyPrevious303 = item;
                        break;
                    case "5f6e8445-b491-43e6-bc50-9064aea82361":
                        dailyPrevious304 = item;
                        break;
                }
            }
            if (daily301 == null || daily302 == null || daily303 == null || daily304 == null || dailyPrevious301 == null || dailyPrevious302 == null || dailyPrevious303 == null || dailyPrevious304 == null) {
                return AjaxJson.error("缺少抄表数据或数据未审批", 412, request, response);
            }
            // 计算结算单数据
            List<HtElectricitySettlementBillItem> itemList = new ArrayList<>();
            HtElectricitySettlementBillItem item1 = new HtElectricitySettlementBillItem();
            HtElectricitySettlementBillItem item2 = new HtElectricitySettlementBillItem();
            item1.setHtElectricitySettlementBillItemModel(new HtElectricitySettlementBillItemModel("846ef7c3-011c-4851-bb5f-67febaaccd66"));
            item2.setHtElectricitySettlementBillItemModel(new HtElectricitySettlementBillItemModel("9fe057a3-4b8c-4640-afcd-12e28c6e33ca"));
            item1.setSettlementStartDate(htElectricitySettlementBillCreateDto.getMonth().atDay(1));
            item2.setSettlementStartDate(htElectricitySettlementBillCreateDto.getMonth().atDay(1));
            item1.setSettlementEndDate(lastDayOfMonth);
            item2.setSettlementEndDate(lastDayOfMonth);
            item1.setMeterReadingStart(dailyPrevious303.getValue());
            item2.setMeterReadingStart(dailyPrevious304.getValue());
            item1.setMeterReadingEnd(daily303.getValue());
            item2.setMeterReadingEnd(daily304.getValue());
            item1.setSettlementUsageKwh(daily303.getValue().subtract(dailyPrevious303.getValue()));
            item2.setSettlementUsageKwh(daily304.getValue().subtract(dailyPrevious304.getValue()));
            item1.setSettlementAmountElectricity(item1.getSettlementUsageKwh().multiply(htElectricityPrice.getPrice()));
            item2.setSettlementAmountElectricity(item2.getSettlementUsageKwh().multiply(htElectricityPrice.getPrice()));
            item1.setGridLineLossFee(htElectricityPrice.getPrice().multiply(BigDecimal.valueOf(285)).multiply(item1.getSettlementUsageKwh().divide(daily301.getValue().subtract(dailyPrevious301.getValue()), 16, RoundingMode.HALF_UP)));
            item2.setGridLineLossFee(htElectricityPrice.getPrice().multiply(BigDecimal.valueOf(48)).multiply(item2.getSettlementUsageKwh().divide(daily302.getValue().subtract(dailyPrevious302.getValue()), 16, RoundingMode.HALF_UP)));
            item1.setComprehensiveErrorCorrectionFee(htElectricityPrice.getPrice().multiply(BigDecimal.valueOf(usage1.getElectricity()).subtract(daily301.getValue().subtract(dailyPrevious301.getValue()))).multiply(item1.getSettlementUsageKwh().divide(daily301.getValue().subtract(dailyPrevious301.getValue()), 16, RoundingMode.HALF_UP)));
            item2.setComprehensiveErrorCorrectionFee(htElectricityPrice.getPrice().multiply(BigDecimal.valueOf(usage2.getElectricity()).subtract(daily302.getValue().subtract(dailyPrevious302.getValue()))).multiply(item2.getSettlementUsageKwh().divide(daily302.getValue().subtract(dailyPrevious302.getValue()), 16, RoundingMode.HALF_UP)));
            item1.setTotalSettlementAmount(item1.getSettlementAmountElectricity().add(item1.getGridLineLossFee()).add(item1.getComprehensiveErrorCorrectionFee()));
            item2.setTotalSettlementAmount(item2.getSettlementAmountElectricity().add(item2.getGridLineLossFee()).add(item2.getComprehensiveErrorCorrectionFee()));
            itemList.add(item1);
            itemList.add(item2);
            htElectricitySettlementBill.setSumPrice(itemList.stream().map(HtElectricitySettlementBillItem::getTotalSettlementAmount).reduce(BigDecimal::add).orElse(BigDecimal.ZERO));
            htElectricitySettlementBillService.create(htElectricitySettlementBill, itemList);
            // 返回成功响应
            return AjaxJson.success(request, response);
        }
        // 6号线供电合同（厦门段）与（漳州段）
        else if (Objects.equals(htElectricitySettlementBillId, "384fe4c8-3edf-4213-9bae-11a501271ccf") || Objects.equals(htElectricitySettlementBillId, "6c73acc6-a713-4d0e-b50e-01282faa983e")) {
            // 查询结算电量是否录入
            HtElectricityUsage usage = new HtElectricityUsage();
            usage.setMonth(htElectricitySettlementBill.getMonth());
            List<HtElectricityUsage> usageList = htElectricityUsageService.findList(usage);
            HtElectricityUsage usage1 = null;
            HtElectricityUsage usage2 = null;
            HtElectricityUsage usageI = null;
            HtElectricityUsage usageII = null;
            for (HtElectricityUsage item : usageList) {
                switch (item.getAmmeter().getId()) {
                    case "3256e851-429e-4ad0-a2a6-339da649d4d3":
                        usage1 = item;
                        break;
                    case "796c5d5d-904c-4b87-8a12-1d89fd86627e":
                        usage2 = item;
                        break;
                    case "64541120-94c4-47d1-ab14-ce977b1d7f6e":
                        usageI = item;
                        break;
                    case "21eea103-bca0-4591-938e-0c2ecec418fb":
                        usageII = item;
                        break;
                }
            }
            if (usage1 == null || usage2 == null || usageI == null || usageII == null) {
                return AjaxJson.error("缺少结算电量", 411, request, response);
            }
            // 查询抄表数据是否完整
            // 获取当前月份的最后一天
            LocalDate lastDayOfMonth = htElectricitySettlementBillCreateDto.getMonth().atEndOfMonth();
            // 获取上个月的最后一天
            LocalDate lastDayOfPreviousMonth = htElectricitySettlementBillCreateDto.getMonth().minusMonths(1).atEndOfMonth();

            HtMeterReadingDaily daily331 = null;
            HtMeterReadingDaily daily332 = null;
            HtMeterReadingDaily daily341 = null;
            HtMeterReadingDaily daily342 = null;
            HtMeterReadingDaily dailyDMP3047 = null;
            HtMeterReadingDaily dailyDMP4044 = null;
            HtMeterReadingDaily dailyMLZXP1081 = null;
            HtMeterReadingDaily dailyMLZXP2071 = null;
            HtMeterReadingDaily dailyLDX301 = null;
            HtMeterReadingDaily dailyLDX302 = null;
            HtMeterReadingDaily dailySTCLD311 = null;
            HtMeterReadingDaily dailySTCLD312 = null;
            HtMeterReadingDaily dailySTCLD313 = null;
            HtMeterReadingDaily dailySTCLD314 = null;
            HtMeterReadingDaily dailySTCLD315 = null;
            HtMeterReadingDaily dailySTCLD316 = null;
            HtMeterReadingDaily dailySTCLD322 = null;
            HtMeterReadingDaily dailySTCLD324 = null;
            HtMeterReadingDaily dailySTCLD331 = null;
            HtMeterReadingDaily dailyPrevious331 = null;
            HtMeterReadingDaily dailyPrevious332 = null;
            HtMeterReadingDaily dailyPrevious341 = null;
            HtMeterReadingDaily dailyPrevious342 = null;
            HtMeterReadingDaily dailyPreviousDMP3047 = null;
            HtMeterReadingDaily dailyPreviousDMP4044 = null;
            HtMeterReadingDaily dailyPreviousMLZXP1081 = null;
            HtMeterReadingDaily dailyPreviousMLZXP2071 = null;
            HtMeterReadingDaily dailyPreviousLDX301 = null;
            HtMeterReadingDaily dailyPreviousLDX302 = null;
            HtMeterReadingDaily dailyPreviousSTCLD311 = null;
            HtMeterReadingDaily dailyPreviousSTCLD312 = null;
            HtMeterReadingDaily dailyPreviousSTCLD313 = null;
            HtMeterReadingDaily dailyPreviousSTCLD314 = null;
            HtMeterReadingDaily dailyPreviousSTCLD315 = null;
            HtMeterReadingDaily dailyPreviousSTCLD316 = null;
            HtMeterReadingDaily dailyPreviousSTCLD322 = null;
            HtMeterReadingDaily dailyPreviousSTCLD324 = null;
            HtMeterReadingDaily dailyPreviousSTCLD331 = null;
            HtMeterReadingDaily daily = new HtMeterReadingDaily();
            daily.setDate(lastDayOfMonth);
            // todo 添加数据审批判断
            List<HtMeterReadingDaily> dailyList = htMeterReadingDailyService.findList(daily).stream().filter(item -> item.getIsApproval() == true).toList();
            for (HtMeterReadingDaily item : dailyList) {
                switch (item.getTask().getId()) {
                    case "fdc86eea-73d2-4b55-9780-7ece4fc5d12e":
                        daily331 = item;
                        break;
                    case "418b1691-2e74-4cf3-8511-0fa9fc07134b":
                        daily332 = item;
                        break;
                    case "6da00eca-6cfd-433f-ac89-0d705a3af467":
                        daily341 = item;
                        break;
                    case "910cbc61-82fd-487a-851a-caf85f870d4c":
                        daily342 = item;
                        break;
                    case "8fb1f2a5-06a2-49be-bd53-756969bd44f2":
                        dailyDMP3047 = item;
                        break;
                    case "4ca494af-69b8-49bc-bd40-d47c00034f95":
                        dailyDMP4044 = item;
                        break;
                    case "8457ff09-df51-42e4-b487-6dbe7345b7dc":
                        dailyMLZXP1081 = item;
                        break;
                    case "375f4b82-292d-49ed-a3f4-ba9451e93a17":
                        dailyMLZXP2071 = item;
                        break;
                    case "d29748f7-d5de-45ac-b2b0-5ae718e5f519":
                        dailyLDX301 = item;
                        break;
                    case "ecdd171b-4470-472c-a68b-a6707a65b826":
                        dailyLDX302 = item;
                        break;
                    case "65444529-5628-48ce-9f12-da330e3cbaa1":
                        dailySTCLD311 = item;
                        break;
                    case "46d12411-326e-4025-b25e-4b8fff8f1722":
                        dailySTCLD312 = item;
                        break;
                    case "70414789-6762-4b78-b2e4-a0a0467ce7cd":
                        dailySTCLD313 = item;
                        break;
                    case "2f171fae-cad4-4865-afc2-ce0027f06acf":
                        dailySTCLD314 = item;
                        break;
                    case "4b6efff8-939a-45ef-8c5d-a7bad3b5c76c":
                        dailySTCLD315 = item;
                        break;
                    case "5b937b51-3493-4c20-85b9-003f694c6939":
                        dailySTCLD316 = item;
                        break;
                    case "93ed655f-947c-45cd-844f-db425c5ed584":
                        dailySTCLD322 = item;
                        break;
                    case "a114c6c4-e738-4db3-8f19-227e8fc404dc":
                        dailySTCLD324 = item;
                        break;
                    case "8807ed1f-a49d-4e03-bc8c-c57c33f82868":
                        dailySTCLD331 = item;
                        break;
                }
            }
            HtMeterReadingDaily dailyPrevious = new HtMeterReadingDaily();
            dailyPrevious.setDate(lastDayOfPreviousMonth);
            List<HtMeterReadingDaily> dailyPreviousList = htMeterReadingDailyService.findList(dailyPrevious).stream().filter(item -> item.getIsApproval() == true).toList();
            for (HtMeterReadingDaily item : dailyPreviousList) {
                switch (item.getTask().getId()) {
                    case "fdc86eea-73d2-4b55-9780-7ece4fc5d12e":
                        dailyPrevious331 = item;
                        break;
                    case "418b1691-2e74-4cf3-8511-0fa9fc07134b":
                        dailyPrevious332 = item;
                        break;
                    case "6da00eca-6cfd-433f-ac89-0d705a3af467":
                        dailyPrevious341 = item;
                        break;
                    case "910cbc61-82fd-487a-851a-caf85f870d4c":
                        dailyPrevious342 = item;
                        break;
                    case "8fb1f2a5-06a2-49be-bd53-756969bd44f2":
                        dailyPreviousDMP3047 = item;
                        break;
                    case "4ca494af-69b8-49bc-bd40-d47c00034f95":
                        dailyPreviousDMP4044 = item;
                        break;
                    case "8457ff09-df51-42e4-b487-6dbe7345b7dc":
                        dailyPreviousMLZXP1081 = item;
                        break;
                    case "375f4b82-292d-49ed-a3f4-ba9451e93a17":
                        dailyPreviousMLZXP2071 = item;
                        break;
                    case "d29748f7-d5de-45ac-b2b0-5ae718e5f519":
                        dailyPreviousLDX301 = item;
                        break;
                    case "ecdd171b-4470-472c-a68b-a6707a65b826":
                        dailyPreviousLDX302 = item;
                        break;
                    case "65444529-5628-48ce-9f12-da330e3cbaa1":
                        dailyPreviousSTCLD311 = item;
                        break;
                    case "46d12411-326e-4025-b25e-4b8fff8f1722":
                        dailyPreviousSTCLD312 = item;
                        break;
                    case "70414789-6762-4b78-b2e4-a0a0467ce7cd":
                        dailyPreviousSTCLD313 = item;
                        break;
                    case "2f171fae-cad4-4865-afc2-ce0027f06acf":
                        dailyPreviousSTCLD314 = item;
                        break;
                    case "4b6efff8-939a-45ef-8c5d-a7bad3b5c76c":
                        dailyPreviousSTCLD315 = item;
                        break;
                    case "5b937b51-3493-4c20-85b9-003f694c6939":
                        dailyPreviousSTCLD316 = item;
                        break;
                    case "93ed655f-947c-45cd-844f-db425c5ed584":
                        dailyPreviousSTCLD322 = item;
                        break;
                    case "a114c6c4-e738-4db3-8f19-227e8fc404dc":
                        dailyPreviousSTCLD324 = item;
                        break;
                    case "8807ed1f-a49d-4e03-bc8c-c57c33f82868":
                        dailyPreviousSTCLD331 = item;
                        break;
                }
            }
            if (daily331 == null || daily332 == null || daily341 == null || daily342 == null || dailyDMP3047 == null || dailyDMP4044 == null || dailyMLZXP1081 == null || dailyMLZXP2071 == null || dailyLDX301 == null || dailyLDX302 == null || dailySTCLD311 == null || dailySTCLD312 == null || dailySTCLD313 == null || dailySTCLD314 == null || dailySTCLD315 == null || dailySTCLD316 == null || dailySTCLD322 == null || dailySTCLD324 == null || dailySTCLD331 == null || dailyPrevious331 == null || dailyPrevious332 == null || dailyPrevious341 == null || dailyPrevious342 == null || dailyPreviousDMP3047 == null || dailyPreviousDMP4044 == null || dailyPreviousMLZXP1081 == null || dailyPreviousMLZXP2071 == null || dailyPreviousLDX301 == null || dailyPreviousLDX302 == null || dailyPreviousSTCLD311 == null || dailyPreviousSTCLD312 == null || dailyPreviousSTCLD313 == null || dailyPreviousSTCLD314 == null || dailyPreviousSTCLD315 == null || dailyPreviousSTCLD316 == null || dailyPreviousSTCLD322 == null || dailyPreviousSTCLD324 == null || dailyPreviousSTCLD331 == null) {
                return AjaxJson.error("缺少抄表数据或数据未审批", 412, request, response);
            }
            // 计算电量结算单
            // 厦门段
            List<HtElectricitySettlementBillItem> xmdItemList = new ArrayList<>();
            HtElectricitySettlementBillItem xmdItem1 = new HtElectricitySettlementBillItem();
            HtElectricitySettlementBillItem xmdItem2 = new HtElectricitySettlementBillItem();
            HtElectricitySettlementBillItem xmdItem3 = new HtElectricitySettlementBillItem();
            HtElectricitySettlementBillItem xmdItem4 = new HtElectricitySettlementBillItem();
            HtElectricitySettlementBillItem xmdItem5 = new HtElectricitySettlementBillItem();
            HtElectricitySettlementBillItem xmdItem6 = new HtElectricitySettlementBillItem();
            xmdItem1.setHtElectricitySettlementBillItemModel(new HtElectricitySettlementBillItemModel("284c46c8-a9f9-4746-9fee-21b9d6c1dbbc"));
            xmdItem2.setHtElectricitySettlementBillItemModel(new HtElectricitySettlementBillItemModel("38779605-3350-4557-8f9a-6942b37e97a0"));
            xmdItem3.setHtElectricitySettlementBillItemModel(new HtElectricitySettlementBillItemModel("800102b7-bcc6-486e-b49c-5b776883d807"));
            xmdItem4.setHtElectricitySettlementBillItemModel(new HtElectricitySettlementBillItemModel("20a3877e-76a8-4d57-b269-2c0ebf4e56e4"));
            xmdItem5.setHtElectricitySettlementBillItemModel(new HtElectricitySettlementBillItemModel("6601c657-31bd-487f-a0eb-324aaf0594ee"));
            xmdItem6.setHtElectricitySettlementBillItemModel(new HtElectricitySettlementBillItemModel("a290d444-ad53-45fe-b4a1-0ef39ade4133"));
            xmdItem1.setSettlementStartDate(htElectricitySettlementBillCreateDto.getMonth().atDay(1));
            xmdItem2.setSettlementStartDate(htElectricitySettlementBillCreateDto.getMonth().atDay(1));
            xmdItem3.setSettlementStartDate(htElectricitySettlementBillCreateDto.getMonth().atDay(1));
            xmdItem4.setSettlementStartDate(htElectricitySettlementBillCreateDto.getMonth().atDay(1));
            xmdItem5.setSettlementStartDate(htElectricitySettlementBillCreateDto.getMonth().atDay(1));
            xmdItem6.setSettlementStartDate(htElectricitySettlementBillCreateDto.getMonth().atDay(1));
            xmdItem1.setSettlementEndDate(lastDayOfMonth);
            xmdItem2.setSettlementEndDate(lastDayOfMonth);
            xmdItem3.setSettlementEndDate(lastDayOfMonth);
            xmdItem4.setSettlementEndDate(lastDayOfMonth);
            xmdItem5.setSettlementEndDate(lastDayOfMonth);
            xmdItem6.setSettlementEndDate(lastDayOfMonth);
            xmdItem1.setMeterReadingStart(dailyPrevious331.getValue().add(dailyPrevious332.getValue()));
            xmdItem2.setMeterReadingStart(dailyPrevious341.getValue().add(dailyPrevious342.getValue()));
            xmdItem3.setMeterReadingStart(dailyPreviousDMP3047.getValue());
            xmdItem4.setMeterReadingStart(dailyPreviousDMP4044.getValue());
            xmdItem5.setMeterReadingStart(dailyPreviousMLZXP1081.getValue());
            xmdItem6.setMeterReadingStart(dailyPreviousMLZXP2071.getValue());
            xmdItem1.setMeterReadingEnd(daily331.getValue().add(daily332.getValue()));
            xmdItem2.setMeterReadingEnd(daily341.getValue().add(daily342.getValue()));
            xmdItem3.setMeterReadingEnd(dailyDMP3047.getValue());
            xmdItem4.setMeterReadingEnd(dailyDMP4044.getValue());
            xmdItem5.setMeterReadingEnd(dailyMLZXP1081.getValue());
            xmdItem6.setMeterReadingEnd(dailyMLZXP2071.getValue());
            xmdItem1.setSettlementUsageKwh(xmdItem1.getMeterReadingEnd().subtract(xmdItem1.getMeterReadingStart()));
            xmdItem2.setSettlementUsageKwh(xmdItem2.getMeterReadingEnd().subtract(xmdItem2.getMeterReadingStart()));
            xmdItem3.setSettlementUsageKwh(xmdItem3.getMeterReadingEnd().subtract(xmdItem3.getMeterReadingStart()));
            xmdItem4.setSettlementUsageKwh(xmdItem4.getMeterReadingEnd().subtract(xmdItem4.getMeterReadingStart()));
            xmdItem5.setSettlementUsageKwh(xmdItem5.getMeterReadingEnd().subtract(xmdItem5.getMeterReadingStart()));
            xmdItem6.setSettlementUsageKwh(xmdItem6.getMeterReadingEnd().subtract(xmdItem6.getMeterReadingStart()));
            xmdItem1.setSettlementAmountElectricity(xmdItem1.getSettlementUsageKwh().multiply(htElectricityPrice.getPrice()));
            xmdItem2.setSettlementAmountElectricity(xmdItem2.getSettlementUsageKwh().multiply(htElectricityPrice.getPrice()));
            xmdItem3.setSettlementAmountElectricity(xmdItem3.getSettlementUsageKwh().multiply(htElectricityPrice.getPrice()));
            xmdItem4.setSettlementAmountElectricity(xmdItem4.getSettlementUsageKwh().multiply(htElectricityPrice.getPrice()));
            xmdItem5.setSettlementAmountElectricity(xmdItem5.getSettlementUsageKwh().multiply(htElectricityPrice.getPrice()));
            xmdItem6.setSettlementAmountElectricity(xmdItem6.getSettlementUsageKwh().multiply(htElectricityPrice.getPrice()));
            xmdItem1.setGridLineLossFee(BigDecimal.valueOf(0));
            xmdItem2.setGridLineLossFee(BigDecimal.valueOf(0));
            xmdItem3.setGridLineLossFee(null);
            xmdItem4.setGridLineLossFee(null);
            xmdItem5.setGridLineLossFee(null);
            xmdItem6.setGridLineLossFee(null);
            xmdItem1.setComprehensiveErrorCorrectionFee(BigDecimal.valueOf(usage1.getElectricity() - usageI.getElectricity()).subtract(xmdItem1.getSettlementUsageKwh()).multiply(xmdItem1.getSettlementUsageKwh().divide(xmdItem1.getSettlementUsageKwh().add(BigDecimal.valueOf(usageI.getElectricity())), 16, RoundingMode.HALF_UP)).multiply(htElectricityPrice.getPrice()));
            xmdItem2.setComprehensiveErrorCorrectionFee(BigDecimal.valueOf(usage2.getElectricity() - usageII.getElectricity()).subtract(xmdItem2.getSettlementUsageKwh()).multiply(xmdItem2.getSettlementUsageKwh().divide(xmdItem2.getSettlementUsageKwh().add(BigDecimal.valueOf(usageII.getElectricity())), 16, RoundingMode.HALF_UP)).multiply(htElectricityPrice.getPrice()));
            xmdItem3.setComprehensiveErrorCorrectionFee(null);
            xmdItem4.setComprehensiveErrorCorrectionFee(null);
            xmdItem5.setComprehensiveErrorCorrectionFee(null);
            xmdItem6.setComprehensiveErrorCorrectionFee(null);
            xmdItem1.setTotalSettlementAmount(xmdItem1.getSettlementAmountElectricity().add(xmdItem1.getComprehensiveErrorCorrectionFee()));
            xmdItem2.setTotalSettlementAmount(xmdItem2.getSettlementAmountElectricity().add(xmdItem2.getComprehensiveErrorCorrectionFee()));
            xmdItem3.setTotalSettlementAmount(xmdItem3.getSettlementAmountElectricity());
            xmdItem4.setTotalSettlementAmount(xmdItem4.getSettlementAmountElectricity());
            xmdItem5.setTotalSettlementAmount(xmdItem5.getSettlementAmountElectricity());
            xmdItem6.setTotalSettlementAmount(xmdItem6.getSettlementAmountElectricity());
            xmdItemList.add(xmdItem1);
            xmdItemList.add(xmdItem2);
            xmdItemList.add(xmdItem3);
            xmdItemList.add(xmdItem4);
            xmdItemList.add(xmdItem5);
            xmdItemList.add(xmdItem6);

            // 漳州段
            List<HtElectricitySettlementBillItem> zzdItemList = new ArrayList<>();
            HtElectricitySettlementBillItem zzdItem1 = new HtElectricitySettlementBillItem();
            HtElectricitySettlementBillItem zzdItem2 = new HtElectricitySettlementBillItem();
            HtElectricitySettlementBillItem zzdItem3 = new HtElectricitySettlementBillItem();
            zzdItem1.setHtElectricitySettlementBillItemModel(new HtElectricitySettlementBillItemModel("1d16f67f-ce5c-4f40-b98a-63778ba28021"));
            zzdItem2.setHtElectricitySettlementBillItemModel(new HtElectricitySettlementBillItemModel("afbc48ed-38cd-4e95-88a2-c86fff1bf57f"));
            zzdItem3.setHtElectricitySettlementBillItemModel(new HtElectricitySettlementBillItemModel("c0508d2a-fd09-41b0-a40d-75e0e5b9e29e"));
            zzdItem1.setSettlementStartDate(htElectricitySettlementBillCreateDto.getMonth().atDay(1));
            zzdItem2.setSettlementStartDate(htElectricitySettlementBillCreateDto.getMonth().atDay(1));
            zzdItem3.setSettlementStartDate(htElectricitySettlementBillCreateDto.getMonth().atDay(1));
            zzdItem1.setSettlementEndDate(lastDayOfMonth);
            zzdItem2.setSettlementEndDate(lastDayOfMonth);
            zzdItem3.setSettlementEndDate(lastDayOfMonth);
            zzdItem1.setMeterReadingStart(dailyPreviousLDX301.getValue());
            zzdItem2.setMeterReadingStart(dailyPreviousLDX302.getValue());
            zzdItem3.setMeterReadingStart(dailyPreviousSTCLD311.getValue().add(dailyPreviousSTCLD312.getValue()).add(dailyPreviousSTCLD313.getValue()).add(dailyPreviousSTCLD314.getValue()).add(dailyPreviousSTCLD315.getValue()).add(dailyPreviousSTCLD316.getValue()).add(dailyPreviousSTCLD322.getValue()).add(dailyPreviousSTCLD324.getValue()).add(dailyPreviousSTCLD331.getValue()));
            zzdItem1.setMeterReadingEnd(dailyLDX301.getValue());
            zzdItem2.setMeterReadingEnd(dailyLDX302.getValue());
            zzdItem3.setMeterReadingEnd(dailySTCLD311.getValue().add(dailySTCLD312.getValue()).add(dailySTCLD313.getValue()).add(dailySTCLD314.getValue()).add(dailySTCLD315.getValue()).add(dailySTCLD316.getValue()).add(dailySTCLD322.getValue()).add(dailySTCLD324.getValue()).add(dailySTCLD331.getValue()));
            zzdItem1.setSettlementUsageKwh(zzdItem1.getMeterReadingEnd().subtract(zzdItem1.getMeterReadingStart()));
            zzdItem2.setSettlementUsageKwh(zzdItem2.getMeterReadingEnd().subtract(zzdItem2.getMeterReadingStart()));
            zzdItem3.setSettlementUsageKwh(zzdItem3.getMeterReadingEnd().subtract(zzdItem3.getMeterReadingStart()));
            zzdItem1.setSettlementAmountElectricity(zzdItem1.getSettlementUsageKwh().multiply(htElectricityPrice.getPrice()));
            zzdItem2.setSettlementAmountElectricity(zzdItem2.getSettlementUsageKwh().multiply(htElectricityPrice.getPrice()));
            zzdItem3.setSettlementAmountElectricity(zzdItem3.getSettlementUsageKwh().multiply(htElectricityPrice.getPrice()));
            zzdItem1.setGridLineLossFee(null);
            zzdItem2.setGridLineLossFee(null);
            zzdItem3.setGridLineLossFee(null);
            zzdItem1.setComprehensiveErrorCorrectionFee(xmdItem1.getComprehensiveErrorCorrectionFee().add(xmdItem2.getComprehensiveErrorCorrectionFee()).multiply((zzdItem1.getSettlementUsageKwh().add(zzdItem2.getSettlementUsageKwh()).subtract(zzdItem3.getSettlementUsageKwh().multiply(BigDecimal.valueOf(0.8031)))).divide(xmdItem1.getSettlementUsageKwh().add(xmdItem2.getSettlementUsageKwh()), 16, RoundingMode.HALF_UP)));
            zzdItem2.setComprehensiveErrorCorrectionFee(BigDecimal.valueOf(0));
            zzdItem3.setComprehensiveErrorCorrectionFee(BigDecimal.valueOf(0));
            zzdItem1.setTotalSettlementAmount(zzdItem1.getSettlementAmountElectricity().add(zzdItem1.getComprehensiveErrorCorrectionFee()));
            zzdItem2.setTotalSettlementAmount(zzdItem2.getSettlementAmountElectricity());
            zzdItem3.setTotalSettlementAmount(zzdItem3.getSettlementAmountElectricity().multiply(BigDecimal.valueOf(0.8031)));
            zzdItem1.setRemark("因临时供电期间供电方式变化，林埭西站接用电开关以电表内反向总有功数值为准");
            zzdItem2.setRemark("因临时供电期间供电方式变化，林埭西站接用电开关以电表内反向总有功数值为准");
            zzdItem3.setRemark("1、含35kV馈线柜311、331、313、315、316、314、312、322、324间隔；\n2、结算电费已按合同条款规定使用用电量结算金额*80.31%");
            zzdItemList.add(zzdItem1);
            zzdItemList.add(zzdItem2);
            zzdItemList.add(zzdItem3);
            BigDecimal zzdSum = zzdItem1.getTotalSettlementAmount().add(zzdItem2.getTotalSettlementAmount()).subtract(zzdItem3.getTotalSettlementAmount());
            // 如果是厦门段
            if (Objects.equals(htElectricitySettlementBillId, "384fe4c8-3edf-4213-9bae-11a501271ccf")) {
                htElectricitySettlementBill.setSumPrice(xmdItemList.stream().map(HtElectricitySettlementBillItem::getTotalSettlementAmount).reduce(BigDecimal::add).orElse(BigDecimal.ZERO).subtract(zzdSum));
                htElectricitySettlementBill.setSumRemark("厦门段结算电费已扣除角美段结算电费" + zzdSum.setScale(4, RoundingMode.HALF_UP).toPlainString() + "元");
                htElectricitySettlementBillService.create(htElectricitySettlementBill, xmdItemList);
            }
            // 如果是漳州段
            else if (Objects.equals(htElectricitySettlementBillId, "6c73acc6-a713-4d0e-b50e-01282faa983e")) {
                htElectricitySettlementBill.setSumPrice(zzdSum);
                htElectricitySettlementBill.setSumRemark("合计结算电费已按合同条款规定扣除乙方分摊社头车辆段电费" + zzdItem3.getTotalSettlementAmount().setScale(4, RoundingMode.HALF_UP).toPlainString() + "元");
                htElectricitySettlementBillService.create(htElectricitySettlementBill, zzdItemList);
            }
            return AjaxJson.success("导出成功", request, response);
        }
        return AjaxJson.error("未定义表单", 444, request, response);
    }

    @PostMapping("/export")
    @Operation(summary = "导出电量结算单", description = "导出电量结算单信息。")
    public AjaxJson export(@RequestBody GetIdDto idDto, HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 查询数据
        HtElectricitySettlementBill htElectricitySettlementBill = htElectricitySettlementBillService.get(idDto.getId());
        if (htElectricitySettlementBill == null) {
            return AjaxJson.error("数据不存在", HttpStatus.HTTP_NOT_FOUND, request, response);
        }
        HtElectricitySettlementBillItem htElectricitySettlementBillItem = new HtElectricitySettlementBillItem();
        htElectricitySettlementBillItem.setHtElectricitySettlementBill(htElectricitySettlementBill);
        List<HtElectricitySettlementBillItem> list = htElectricitySettlementBillItemService.findList(htElectricitySettlementBillItem);
        // 排序
        list.sort(Comparator.comparing(item -> item.getHtElectricitySettlementBillItemModel().getSortOrder()));
        int type = htElectricitySettlementBill.getHtElectricitySettlementBillModel().getType();
        // 创建表头
        ExportExcel excel = new ExportExcel();
        excel.createSheet("电量结算单");
        // 设置前 13 列的宽度
        if (type == 2 || type == 3) {
            excel.getSheet().setColumnWidth(0, (int) Math.round(1.0687 * 5.49 * 256));
            for (int i = 1; i < 12; i++) {
                excel.getSheet().setColumnWidth(i, (int) Math.round(1.0687 * 10 * 256));
            }
            excel.getSheet().setColumnWidth(12, (int) Math.round(1.0687 * 20 * 256));
        } else {
            for (int i = 0; i < 4; i++) {
                excel.getSheet().setColumnWidth(i, (int) Math.round(1.0687 * 12.13 * 256));
            }
            excel.getSheet().setColumnWidth(4, (int) Math.round(1.0687 * 14.13 * 256));
            for (int i = 5; i < 9; i++) {
                excel.getSheet().setColumnWidth(i, (int) Math.round(1.0687 * 12.13 * 256));
            }
            excel.getSheet().setColumnWidth(9, (int) Math.round(1.0687 * 15.13 * 256));
            excel.getSheet().setColumnWidth(10, (int) Math.round(1.0687 * 16.13 * 256));
            for (int i = 11; i < 13; i++) {
                excel.getSheet().setColumnWidth(i, (int) Math.round(1.0687 * 12.13 * 256));
            }
        }
        // 表格样式
        // 表格抬头
        excel.setFontName("宋体");
        if (type == 2 || type == 3) {
            excel.setFontHeightInPoints((short) 12);
        } else {
            excel.setFontHeightInPoints((short) 14);
        }
        excel.setFontBold(true);
        excel.refreshCellStyle();
        excel.setCellAlignment(HorizontalAlignment.CENTER, VerticalAlignment.CENTER);
        if (type == 2 || type == 3) {
            excel.getCellStyle().setFillForegroundColor(new XSSFColor(Color.decode("#FFFFFF"), new DefaultIndexedColorMap()));
            excel.getCellStyle().setFillPattern(FillPatternType.SOLID_FOREGROUND);
        } else {
            excel.getCellStyle().setFillForegroundColor(new XSSFColor(Color.decode("#F2F2F2"), new DefaultIndexedColorMap()));
            excel.getCellStyle().setFillPattern(FillPatternType.SOLID_FOREGROUND);
        }
        excel.setRowHeight(20);
        excel.createRow().createCell("厦门地铁运营有限公司 ").mergeCells(1, 13);
        excel.createRow().createCell("外单位用电结算清单").mergeCells(1, 13);
        // 设置样式
        excel.setFontHeightInPoints((short) 10);
        excel.setFontBold(false);
        excel.refreshCellStyle();
        excel.setCellAlignment(HorizontalAlignment.CENTER, VerticalAlignment.CENTER);
        // 填充日期
        excel.createRow().createCell(LocalDate.now().format(DateTimeFormatter.ofPattern("日期：yyyy年MM月dd日"))).mergeCells(1, 13);
        // 填充基本信息
        if (type == 2 || type == 3) {
            // 10.5
            excel.setFontHeightInPoints(10.5);
        } else {
            excel.setFontHeightInPoints((short) 10);
        }
        excel.refreshCellStyle();
        excel.setCellAlignment(HorizontalAlignment.LEFT, VerticalAlignment.CENTER);
        excel.createRow().createCell("客户名称：" + htElectricitySettlementBill.getHtElectricitySettlementBillModel().getCustomerName()).mergeCells(1, 13);
        excel.createRow().createCell("项目名称：" + htElectricitySettlementBill.getHtElectricitySettlementBillModel().getProjectName()).mergeCells(1, 13);
        excel.createRow().createCell("合同号及合同名称：" + htElectricitySettlementBill.getHtElectricitySettlementBillModel().getContractNoAndName()).mergeCells(1, 13);
        // 主表部分
        // 主表表头
        if (type == 2 || type == 3) {
            excel.setFontBold(false);
            excel.setRowHeight(-1);
        } else {
            excel.setFontBold(true);
            excel.setRowHeight(49.5F);
        }
        excel.refreshCellStyle();
        excel.getCellStyle().setBorderTop(BorderStyle.THIN);
        excel.getCellStyle().setBorderBottom(BorderStyle.THIN);
        excel.getCellStyle().setBorderLeft(BorderStyle.THIN);
        excel.getCellStyle().setBorderRight(BorderStyle.THIN);
        excel.getCellStyle().setWrapText(true);
        excel.setCellAlignment(HorizontalAlignment.CENTER, VerticalAlignment.CENTER);
        excel.createRow().createCell("序号", "接用类型", "接用地点", "结算起止时间", "表计开始读数\n（千瓦时）", "表计最终读数\n（千瓦时）", "用电结算用量\n（千瓦时）", "结算单价\n（元）", "用电量结算\n金额\n（元）", "国网线损费用\n（元）", "综合误差修正费用\n（元）", "结算金额\n（元）", "备注");
        // 填充数据
        if (type == 2 || type == 3) {
            excel.setRowHeight(-1);
        } else {
            excel.setRowHeight(40);
        }
        excel.setFontBold(false);
        excel.refreshCellStyle();
        excel.getCellStyle().setWrapText(true);
        excel.getCellStyle().setBorderTop(BorderStyle.THIN);
        excel.getCellStyle().setBorderBottom(BorderStyle.THIN);
        excel.getCellStyle().setBorderLeft(BorderStyle.THIN);
        excel.getCellStyle().setBorderRight(BorderStyle.THIN);
        excel.setCellAlignment(HorizontalAlignment.CENTER, VerticalAlignment.CENTER);
        for (int i = 0; i < list.size(); i++) {
            HtElectricitySettlementBillItem item = list.get(i);
            HtElectricitySettlementBillItemModel model = item.getHtElectricitySettlementBillItemModel();
            String index = String.valueOf(i + 1);
            String connectionType = model.getConnectionType();
            String connectionLocation = model.getConnectionLocation();
            String startEndDate = item.getSettlementStartDate().format(DateTimeFormatter.ofPattern("yyyy年MM月dd日-")) + item.getSettlementEndDate().format(DateTimeFormatter.ofPattern("yyyy年MM月dd日"));
            String meterReadingStart = item.getMeterReadingStart().setScale(4, RoundingMode.HALF_UP).toPlainString();
            String meterReadingEnd = item.getMeterReadingEnd().setScale(4, RoundingMode.HALF_UP).toPlainString();
            String settlementUsageKwh = item.getSettlementUsageKwh().setScale(4, RoundingMode.HALF_UP).toPlainString();
            String electricityPrice = htElectricitySettlementBill.getHtElectricityPrice().getPrice().setScale(8, RoundingMode.HALF_UP).toPlainString();
            String settlementAmountElectricity = item.getSettlementAmountElectricity().doubleValue() == 0 ? "0" : item.getSettlementAmountElectricity().setScale(4, RoundingMode.HALF_UP).toPlainString();
            String gridLineLossFee = item.getGridLineLossFee() == null ? "\\" : item.getGridLineLossFee().doubleValue() == 0 ? "0" : item.getGridLineLossFee().setScale(8, RoundingMode.HALF_UP).toPlainString();
            String comprehensiveErrorCorrectionFee = item.getComprehensiveErrorCorrectionFee() == null ? "\\" : item.getComprehensiveErrorCorrectionFee().doubleValue() == 0 ? "0" : item.getComprehensiveErrorCorrectionFee().setScale(6, RoundingMode.HALF_UP).toPlainString();
            String totalSettlementAmount = item.getTotalSettlementAmount().doubleValue() == 0 ? "0" : item.getTotalSettlementAmount().setScale(4, RoundingMode.HALF_UP).toPlainString();
            String remark = item.getRemark();
            if (type == 3 && i == 0) {
                excel.createRow().createCell(index, connectionType, connectionLocation, startEndDate, meterReadingStart, meterReadingEnd, settlementUsageKwh, electricityPrice, settlementAmountElectricity, gridLineLossFee, comprehensiveErrorCorrectionFee, totalSettlementAmount);
                excel.createCell(remark).mergeCells(2, 1);
                continue;
            }
            excel.createRow().createCell(index, connectionType, connectionLocation, startEndDate, meterReadingStart, meterReadingEnd, settlementUsageKwh, electricityPrice, settlementAmountElectricity, gridLineLossFee, comprehensiveErrorCorrectionFee, totalSettlementAmount, remark);
        }
        // 计算合计
        String sum = htElectricitySettlementBill.getSumPrice().setScale(2, RoundingMode.HALF_UP).toPlainString();
        String sumRemark = htElectricitySettlementBill.getSumRemark() == null ? "" : htElectricitySettlementBill.getSumRemark();
        excel.createRow().createCell("合计", "", "", "", "", "", "", "", "", "", "", sum, sumRemark);
        // 填充数据说明
        excel.setRowHeight(25);
        excel.refreshCellStyle();
        excel.getCellStyle().setBorderTop(BorderStyle.THIN);
        excel.getCellStyle().setBorderBottom(BorderStyle.THIN);
        excel.getCellStyle().setBorderLeft(BorderStyle.THIN);
        excel.getCellStyle().setBorderRight(BorderStyle.THIN);
        excel.setCellAlignment(HorizontalAlignment.LEFT, VerticalAlignment.CENTER);
        if (type == 2 || type == 3) {
            excel.createRow().createCell("说明：用电量的单位为（千瓦时）。").mergeCells(1, 11);
            excel.createCell("", "");
        } else {
            excel.createRow().createCell("说明：用电量的单位为（千瓦时）。合计结算金额保留两位小数。").mergeCells(1, 13);
        }
        // 填充签字区
        if (type == 2 || type == 3) {
            excel.setRowHeight(100);
        } else {
            excel.setRowHeight(85);
        }
        excel.refreshCellStyle();
        excel.getCellStyle().setWrapText(true);
        excel.getCellStyle().setBorderTop(BorderStyle.THIN);
        excel.getCellStyle().setBorderBottom(BorderStyle.THIN);
        excel.getCellStyle().setBorderLeft(BorderStyle.THIN);
        excel.getCellStyle().setBorderRight(BorderStyle.THIN);
        excel.setCellAlignment(HorizontalAlignment.LEFT, VerticalAlignment.TOP);
        if (type == 2 || type == 3) {
            if (type == 2) {
                excel.createRow().createCell("甲方： " + htElectricitySettlementBill.getHtElectricitySettlementBillModel().getPartyAName() + "         乙方：" + htElectricitySettlementBill.getHtElectricitySettlementBillModel().getPartyBName() + ":\n\n\n经办人(签字）：                     经办人(签字）：\n").mergeCells(1, 11);
                excel.createCell("", "");
            } else {
                excel.createRow().createCell("甲方： " + htElectricitySettlementBill.getHtElectricitySettlementBillModel().getPartyAName() + "         乙方：" + htElectricitySettlementBill.getHtElectricitySettlementBillModel().getPartyBName() + "\n\n经办人(签字）：                     经办人(签字）：\n\n" +
                        htElectricitySettlementBill.getHtElectricitySettlementBillModel().getPartyCName() + "\n\n经办人（签字）：").mergeCells(1, 13);
            }
        } else {
            excel.createRow().createCell("甲方：" + htElectricitySettlementBill.getHtElectricitySettlementBillModel().getPartyAName() + "\n\n\n经办人(签字）：").mergeCells(1, 7);
            excel.createCell("乙方：" + htElectricitySettlementBill.getHtElectricitySettlementBillModel().getPartyBName() + "\n\n\n经办人(签字）：").mergeCells(1, 6);
            // 填充丙方（如果有的话）
            if (htElectricitySettlementBill.getHtElectricitySettlementBillModel().getPartyCName() != null) {
                excel.createRow().createCell("丙方：" + htElectricitySettlementBill.getHtElectricitySettlementBillModel().getPartyCName() + "\n\n\n经办人(签字）：").mergeCells(1, 13);
            }
        }
        // 说明
        excel.setRowHeight(25);
        excel.refreshCellStyle();
        if (type == 2 || type == 3) {
            excel.getCellStyle().setFillForegroundColor(new XSSFColor(Color.decode("#FFFFFF"), new DefaultIndexedColorMap()));
            excel.getCellStyle().setFillPattern(FillPatternType.SOLID_FOREGROUND);
        } else {
            excel.getCellStyle().setFillForegroundColor(new XSSFColor(Color.decode("#F2F2F2"), new DefaultIndexedColorMap()));
            excel.getCellStyle().setFillPattern(FillPatternType.SOLID_FOREGROUND);
        }
        excel.setCellAlignment(HorizontalAlignment.LEFT, VerticalAlignment.CENTER);
        excel.createRow().createCell("说明", "", "", "", "", "", "", "", "", "", "", "", "");

        excel.refreshCellStyle();
        excel.getCellStyle().setWrapText(true);
        if (type == 2 || type == 3) {
            excel.setRowHeight(-1);
        } else {
            excel.setRowHeight(64.5F);
        }
        if (type == 2 || type == 3) {
            excel.getCellStyle().setFillForegroundColor(new XSSFColor(Color.decode("#FFFFFF"), new DefaultIndexedColorMap()));
            excel.getCellStyle().setFillPattern(FillPatternType.SOLID_FOREGROUND);
        } else {
            excel.getCellStyle().setFillForegroundColor(new XSSFColor(Color.decode("#F2F2F2"), new DefaultIndexedColorMap()));
            excel.getCellStyle().setFillPattern(FillPatternType.SOLID_FOREGROUND);
        }
        excel.setCellAlignment(HorizontalAlignment.LEFT, VerticalAlignment.CENTER);
        excel.createRow().createCell(htElectricitySettlementBill.getHtElectricitySettlementBillModel().getRemark()).mergeCells(1, 13);

        excel.write(response, "电量结算单.xlsx");
        return null;
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除电量结算单", description = "根据ID删除电量结算单信息。", parameters = {@Parameter(name = "ids", description = "电量结算单ID列表，多个ID用英文逗号分隔。")})
    public AjaxJson delete(@RequestParam String ids, HttpServletRequest request, HttpServletResponse response) {
        // 检查ID参数是否为空，为空则返回错误响应
        if (ids == null) {
            return AjaxJson.error("参数错误", HttpStatus.HTTP_BAD_REQUEST, request, response);
        }
        // 调用服务层方法，执行删除操作
        htElectricitySettlementBillService.delete(ids);
        // 返回成功响应
        return AjaxJson.success(request, response);
    }
}
